#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

int cmpfunc (const void * a, const void * b)
{
   return strcmp(a,b)>0?1:0;
}

void printdir(char *dir, int all)
{
    DIR *dp;
    struct dirent *entry;
    struct stat statbuf;
    char filename[100][100];
    int i=0;

    if((dp = opendir(dir)) == NULL)
    {
        fprintf(stderr, "cannot open directory: %s\n", dir);
        return;
    }
    chdir(dir);
    while((entry = readdir(dp)) != NULL)
    {
        lstat(entry->d_name, &statbuf);
	if(all==1 || '.'!=entry->d_name[0]){
		strcpy(filename[i], entry->d_name);
		i++;
	}
    }
    chdir("..");
    closedir(dp);
    qsort(filename, i, 100*sizeof(char), cmpfunc);
    for(int j=0;j<i;j++){
        printf("%s\t", filename[j]);
    }
    printf("\n");
}

int main(int argc, char* argv[])
{
    char topdir[100] = ".";
    int all=0;
    for(int i=1;i<argc;i++){
    	if (strcmp("-a",argv[i])==0){
                all = 1;
        }else
        strcpy(topdir, argv[i]);
    }
    
    printdir(topdir, all);
    exit(0);
}
